const Base = require("./base");
const moment = require("moment");
// 查询字段并转换为数字
const publicSQL =
  "CAST(COALESCE(SUM(today_count),0) AS SIGNED) AS total_count,CAST(COALESCE(SUM(today_gather_count),0) AS SIGNED) AS total_gather_count,CAST(COALESCE(SUM(incence_count),0) AS SIGNED) AS total_incence_count";
module.exports = class MeritService extends Base {
  putTodayLog(params) {
    const { uid, type, mantra_id = 1 } = params;
    const expr = `WHERE uid='${uid}' AND type='${type}' AND mantra_id='${mantra_id}' AND TO_DAYS(create_time)=TO_DAYS(now())`;
    const db = this.app.mysql.use("user");
    return db
      .query(`SELECT * FROM merit_today_log ${expr};`)
      .then((res) => res[0][0])
      .then((res) => {
        if (res) {
          const { replacements, values } = this.installParams(params, 2);
          return db
            .query(`UPDATE merit_today_log SET ${values} ${expr}`, {
              replacements,
            })
            .then((res) => res[0].info);
        } else {
          const { keys, replacements, values } = this.installParams(params);
          return db.query(
            `INSERT INTO merit_today_log(${keys}) VALUES(${values})`,
            {
              replacements,
            }
          );
        }
      });
  }
  getTodayLog(params) {
    const { uid, type } = params;
    let expr = `WHERE uid='${uid}'`;
    if (type) {
      expr += ` AND type='${type}'`;
    }
    let sql = `
    SELECT type,${publicSQL} FROM merit_today_log ${expr};
    SELECT mantra_id,${publicSQL} FROM merit_today_log ${expr} GROUP BY mantra_id;
    SELECT mantra_id,today_count,today_gather_count,incence_count,create_time,type FROM merit_today_log ${expr} AND TO_DAYS(create_time)=TO_DAYS(now())`;
    const db = this.app.mysql.use("user");
    return db
      .query(sql)
      .then((res) => res[0])
      .then((res) => {
        const total = res[0][0];
        const defaultTotal = {
          type,
          total_count: 0,
          total_gather_count: 0,
          total_incence_count: 0,
        };
        const defaultMantra = {
          mantra_id: 1,
          today_count: 0,
          today_gather_count: 0,
          incence_count: 0,
          create_time: moment().format("YYYY-MM-DD 00:00:01"),
        };
        const all = res[1];
        if (!all.length)
          return {
            total: defaultTotal,
            type,
            logs: {
              1: {
                ...defaultMantra,
                ...defaultTotal
              },
            },
          };

        const today = res[2];
        const todayMap = {};
        today.forEach((item) => {
          todayMap[item.mantra_id] = item;
        });
        const logs = {};
        all.forEach((item) => {
          logs[item.mantra_id] = Object.assign(
            {},
            defaultMantra,
            item,
            todayMap[item.mantra_id]
          );
        });
        return { total, logs, type };
      });
  }

  getTodayAllLog(uid) {
    let expr = `WHERE uid='${uid}'`;
    let sql = `
    SELECT ${publicSQL} FROM merit_today_log ${expr};
    SELECT CAST(COALESCE(SUM(today_count),0) AS SIGNED) AS today_count,CAST(COALESCE(SUM(today_gather_count),0) AS SIGNED) AS today_gather_count,CAST(COALESCE(SUM(incence_count),0) AS SIGNED) AS incence_count FROM merit_today_log ${expr} AND TO_DAYS(create_time)=TO_DAYS(now())`;
    const db = this.app.mysql.use("user");
    return db
      .query(sql)
      .then((res) => res[0])
      .then((res) => {
        const total_count = res[0][0] || {};
        const today_count = res[1][0] || {};
        return { ...total_count, ...today_count, type: "ALL" };
      });
  }
  totalLogByType(params) {
    const { uid, type, version } = params;
    let expr = `WHERE uid='${uid}'`;
    if (type) {
      expr += ` AND type='${type}'`;
    }
    let sql = `SELECT ${publicSQL} FROM merit_today_log ${expr} GROUP BY uid;
    SELECT today_count,today_gather_count,incence_count,create_time,type FROM merit_today_log ${expr} AND TO_DAYS(create_time)=TO_DAYS(now())`;
    const db = this.app.mysql.use("user");
    return db
      .query(sql)
      .then((res) => res[0])
      .then((res) => {
        const defaultValue = {
          today_count: 0,
          today_gather_count: 0,
          incence_count: 0,
          create_time: moment().format("YYYY-MM-DD 00:00:01"),
        };
        let allLog = res[0][0];
        let todayLog = res[1];
        if (type) {
          todayLog = res[1][0] || Object.assign({ type }, defaultValue);
        }
        if (version > "1.0.3") {
          return {
            allLog,
            todayLog,
          };
        } else {
          return Object.assign({ type }, allLog, defaultValue);
        }
      });
  }

  totalLogByUserType(params) {
    return this.app.mysql
      .use("user")
      .query(
        `SELECT * FROM merit_today_log WHERE type='${params.type}' AND uid='${params.uid}'`
      )
      .then((res) => res[0][0]);
  }

  // 用户捐赠日志
  getDonateLog(params) {
    return this.app.mysql
      .use("user")
      .query(
        `SELECT * FROM merit_donate_log WHERE uid='${params.uid}' GROUP BY uid`
      )
      .then((res) => res[0][0]);
  }
  putDonateLog(params) {
    const db = this.app.mysql.use("user");
    const { keys, replacements, values } = this.installParams(params);
    return db.query(`INSERT INTO merit_donate_log(${keys}) VALUES(${values})`, {
      replacements,
    });
  }

  getCount(params) {
    const db = this.app.mysql.use("user");
    const { uid } = params;
    return db
      .query(
        `SELECT uid,${publicSQL} FROM merit_today_log WHERE uid='${uid}' GROUP BY uid;
        SELECT uid,CAST(COALESCE(SUM(donate_count),0) AS SIGNED) AS donate_count FROM merit_donate_log WHERE uid='${uid}' GROUP BY uid;`
      )
      .then((res) => res[0])
      .then((res) => {
        const totalLog = res[0][0];
        const donateLog = res[1][0] || { donate_count: "0" };
        return Object.assign({}, totalLog, donateLog);
      });
  }

  list() {
    const db = this.app.mysql.use("user");
    return db
      .query(
        `SELECT province,${publicSQL} FROM merit_today_log GROUP BY province ORDER BY total_count DESC;
        SELECT province,CAST(COALESCE(SUM(donate_count),0) AS SIGNED) AS donate_count FROM merit_donate_log AS b GROUP BY province
        ORDER BY donate_count DESC;
        `
      )
      .then((res) => res[0])
      .then((res) => {
        const totalLog = res[0];
        const donateLog = res[1];
        const map = {};
        donateLog.forEach((item) => {
          const province = item.province;
          map[province] = item;
        });

        totalLog.forEach((item) => {
          const province = item.province;
          const donateItem = map[province] || { donate_count: "0" };
          const keys = Object.keys(donateItem);
          keys.forEach((key) => {
            item[key] = donateItem[key] || 0;
          });
        });
        return totalLog;
      });
  }
  province(province) {
    const db = this.app.mysql.use("user");
    return db
      .query(
        `SELECT CAST(COALESCE(SUM(today_count),0) AS SIGNED) AS total_count FROM merit_today_log WHERE province LIKE'%${province}%'
        GROUP BY province`
      )
      .then((res) => res[0][0]);
  }
};
